/*
 * BackupDataDAO.java
 *
 * Created on April 7, 2007, 8:43 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package edu.byu.isys413.group1E.data;

import edu.byu.isys413.group1E.handlers.Cache;
import edu.byu.isys413.group1E.handlers.ConnectionPool;
import edu.byu.isys413.group1E.handlers.ConnectionPoolException;
import edu.byu.isys413.group1E.handlers.DataException;
import edu.byu.isys413.group1E.handlers.GUID;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import org.apache.commons.fileupload.FileItem;

/** This class is created to provide interaction with the BackupData table in the database.
 *
 * @author tkulbeth
 */
public class BackupDataDAO{
    
    /** Contains an instance of BackupDataDAO*/
    private static BackupDataDAO instance = null;
    
    /** Creates a new instance of BackupDataDAO */
    public BackupDataDAO() {
    }
    
    /**Retrieves an instance of the BackupDataDAO object
     *
     * @return a current singleton instance of the BackupDataDAO class
     */
    public static synchronized BackupDataDAO getInstance() {
        if (instance == null) {
            instance = new BackupDataDAO();
        }
        return instance;
    }
    
    ///////////////////////////////////////////////////////////////////////////////
    /////////   CREATE
    /**
     * Creates a new BackupDataBO object with a newly generated GUID.
     * 
     * @return a newly created BackupDataBO with unique GUID
     * @throws java.lang.Exception to catch any errors in the creation process.
     */
    public BackupDataBO create() throws Exception{
        String id = GUID.generate();
        BackupDataBO bo = new BackupDataBO(id);
        Cache c = Cache.getInstance();
        c.put(bo.getId(), bo);
        return bo;
    }
    
    //////////////////////////////////////////////////////////////////////////////
    //////////   READ
    /**
     * This is the public read statement.  It loads an existing BackupData record
     * from the database based on the BackupData id and returns a BackupDataBO.
     * 
     * 
     * @return a BackupDataBO containing the information extracted from the requested
     * tuple in the DB.
     * @param id contains the unique identifier for the record to be read from the DB.
     * @throws edu.byu.isys413.group1E.handlers.DataException handles any errors from data
     * @throws edu.byu.isys413.group1E.handlers.ConnectionPoolException catches any errors with the connection
     */
    public synchronized BackupDataBO read(String id) throws DataException, ConnectionPoolException {
        // check to see if id in the cache
        Cache c = Cache.getInstance();
        BackupDataBO bkData = (BackupDataBO)c.get(id);
        if (bkData != null){
            return bkData;                                                        // if so, return it immediately
        }
        
        //otherwise, get it from the database
        try {
            Connection conn = ConnectionPool.getInstance().get();             // retrieve a database connection from the pool
            bkData = this.read(id, conn);                                              // call read with a connection
            conn.commit();
            ConnectionPool.getInstance().release(conn);                       // release the connection
        }catch (SQLException e) {
            //rollback
            throw new DataException("Could not retrieve record for id = " + id, e);
        }catch (ConnectionPoolException x) {
            //rollback
            throw new ConnectionPoolException("Could not establish connection to database.", x);
        }
        
        // release the connection back to the pool
        return bkData;
    }
    
    
    /**
     * This is the public read statement.  It loads an existing BackupData record
     * from the database based on the BackupData id, using an already existing connection to the DB,
     * and returns a BackupDataBO.
     *
     *
     * @return BackupDataBO
     * @param id contains the given id for the BackupData to be read
     * @param conn contains an already open connection to the DB
     * @throws edu.byu.isys413.group1E.handlers.DataException handles any errors from data
     * @throws java.sql.SQLException catches any errors from the SQL execution
     */
    synchronized BackupDataBO read(String id, Connection conn) throws SQLException, DataException {
        // check to see if id in the cache
        Cache c = Cache.getInstance();
        BackupDataBO bkData = (BackupDataBO)c.get(id);
        if (bkData != null){
            return bkData;                                                        // if so, return it immediately
        }
        
        // if not in the cache, get a result set from
        // a SELECT * FROM table WHERE id=guid
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT thisFileName, fileSize, dateUploaded, fileType, ext, Status, membershipID" +
                " FROM BackupData WHERE BackupID = '" + id + "'");
        conn.commit();
        
        //build the object from the result set
        if (rs.next()) {
            bkData = new BackupDataBO(id);
            bkData.setExt(rs.getString("ext"));
            bkData.setDateUploaded(rs.getDate("dateUploaded").toString());
            bkData.setFileName(rs.getString("thisFileName"));
            bkData.setFileType(rs.getString("fileType"));
            bkData.setFileSize(rs.getDouble("fileSize"));
            bkData.setMembershipID(rs.getString("membershipID"));
            bkData.setStatus(rs.getString("Status"));
            bkData.setAlreadyInDB(true);
            bkData.setIsDirty(false);
            
            // save to the cache
            c.put(bkData.getId(), bkData);
        }else{
            throw new DataException("Object was not found in the database.");
        }
        stmt.close();
        // return the BO
        return bkData;
    }
    
    /**
     * This is a public method to retrieve a list of all BackupData in the DB.
     * 
     * 
     * @return a list of all BackupDataBOs from the DB.
     * @throws edu.byu.isys413.group1E.handlers.DataException handles any errors from data
     * @throws java.sql.SQLException catches any errors from the SQL execution
     * @throws edu.byu.isys413.group1E.handlers.ConnectionPoolException catches any errors with the connection
     */
    public synchronized ArrayList<BackupDataBO> readAllbkData() throws DataException, SQLException, ConnectionPoolException{
        ArrayList<BackupDataBO> bkDataList = new ArrayList<BackupDataBO>();
        //now build the query
        String query = "SELECT BackupID, thisFileName, fileSize, dateUploaded, fileType, ext, Status, membershipID FROM BackupData";
        
        Connection conn = ConnectionPool.getInstance().get();
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        conn.commit();
        
        //extract the elements from the result set and build a list of results
        //build the object from the result set
        //build the object from the result set
        while (rs.next()) {
            BackupDataBO bkData = new BackupDataBO(rs.getString("BackupID"));
            bkData.setExt(rs.getString("ext"));
            bkData.setDateUploaded(rs.getDate("dateUploaded").toString());
            bkData.setFileName(rs.getString("thisFileName"));
            bkData.setFileSize(rs.getDouble("fileSize"));
            bkData.setFileType(rs.getString("fileType"));
            bkData.setMembershipID(rs.getString("membershipID"));
            bkData.setStatus(rs.getString("Status"));
            bkData.setAlreadyInDB(true);
            bkData.setIsDirty(false);
            
            // save to the list
            bkDataList.add(bkData);
        }//while
        
        stmt.close();
        ConnectionPool.getInstance().release(conn);
        return bkDataList;
    }

    /**
     * This is a public method to retrieve a list of all backups for a specified member in the DB.
     * 
     * 
     * @return a list of all BackupDataBOs from the DB.
     * @param memberID contains the id of the member by which the objects will be read
     * @throws edu.byu.isys413.group1E.handlers.DataException handles any errors from data
     * @throws java.sql.SQLException catches any errors from the SQL execution
     * @throws edu.byu.isys413.group1E.handlers.ConnectionPoolException catches any errors with the connection
     */
    public synchronized ArrayList<BackupDataBO> readByMember(String memberID) throws DataException, SQLException, ConnectionPoolException{
        ArrayList<BackupDataBO> bkDataList = new ArrayList<BackupDataBO>();
        //now build the query
        String query = "SELECT BackupID, thisFileName, fileSize, dateUploaded, fileType, ext " +
                "FROM BackupData WHERE MembershipID = '" + memberID + "' AND Status = 'permanent'";
        
        Connection conn = ConnectionPool.getInstance().get();
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        conn.commit();
        
        //extract the elements from the result set and build a list of results
        //build the object from the result set
        //build the object from the result set
        while (rs.next()) {
            BackupDataBO bkData = new BackupDataBO(rs.getString("BackupID"));
            bkData.setExt(rs.getString("ext"));
            bkData.setDateUploaded(rs.getDate("dateUploaded").toString());
            bkData.setFileName(rs.getString("thisFileName"));
            bkData.setFileSize(rs.getDouble("fileSize"));
            bkData.setFileType(rs.getString("fileType"));
            bkData.setMembershipID(memberID);
            bkData.setAlreadyInDB(true);
            bkData.setIsDirty(false);
            
            // save to the list
            bkDataList.add(bkData);
        }//while
        
        stmt.close();
        ConnectionPool.getInstance().release(conn);
        return bkDataList;
    }
    
    //////////////////////////////////
    ///   UPDATE
    
    /**
     * This is the public save method.  It is what is called when
     * the user (controller) wants to save or update an object
     * into the database.
     * 
     * 
     * @param bkDataIn is a BackupDataBO object to be saved
     * @throws edu.byu.isys413.group1E.handlers.DataException handles any errors from data
     * @throws edu.byu.isys413.group1E.handlers.ConnectionPoolException catches any errors with the connection
     */
    public synchronized void save(BackupDataBO bkDataIn) throws DataException, ConnectionPoolException {
        
        try {
            Connection conn = ConnectionPool.getInstance().get();
            try {
                this.save(bkDataIn, conn);                                   // call save with a connection
                conn.commit();
            } catch (ConnectionPoolException ex) {
                conn.rollback();
                ex.printStackTrace();
            } catch (DataException ex) {
                conn.rollback();
                ex.printStackTrace();
            } catch (SQLException ex) {
                conn.rollback();
                ex.printStackTrace();
                throw new SQLException();
            }
            ConnectionPool.getInstance().release(conn);                       // release the connection
        }catch (SQLException e) {
            // rollback
            throw new DataException("Error saving record for Backup ID =" + bkDataIn.getId(), e);
        }catch (ConnectionPoolException x){
            throw new ConnectionPoolException("Could not establish connection to database.", x);
        }
        
        // release the connection back to the pool
        return;
    }
    
    /**
     * This is a package method that is called by the public save (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     * 
     *  By having other DAOs call this save method (rather than update or
     *  insert below, each DAO in a chained save (like the BackupDataDAO calling
     *  MembershipDAO calling InterestDAO save chain) can independently decide
     *  whether to udpate or insert the BO it's saving.
     * 
     * 
     * @param bkData contains the BackupDataBO to be saved
     * @param conn contains the Connection that has been established to the DB
     * @throws edu.byu.isys413.group1E.handlers.DataException handles any errors from data
     * @throws java.sql.SQLException catches any errors from the SQL execution
     * @throws edu.byu.isys413.group1E.handlers.ConnectionPoolException catches any errors with the connection
     */
    public synchronized void save(BackupDataBO bkData, Connection conn) throws SQLException, DataException, ConnectionPoolException {
        // run update or insert
        if (bkData.isIsDirty()) {
            if (bkData.isAlreadyInDB()) {
                update(bkData, conn);
            }else{
                insert(bkData, conn);
            }
            // set the dirty flag to false now that we've saved it
            bkData.setIsDirty(false);
        }
        // touch the cache for the object
        Cache c = Cache.getInstance();
        c.put(bkData.getId(), bkData);
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL udpate statement and make it more readable.  But
     * logically, it's really just a part of save.
     * 
     * 
     * 
     * @param bkData contains the BackupDataBO to be updated to the DB
     * @param conn contains the connection already established with the DB
     * @throws edu.byu.isys413.group1E.handlers.DataException handles any errors from data
     * @throws java.sql.SQLException catches any errors from the SQL execution
     */
    private synchronized void update(BackupDataBO bkData, Connection conn) throws SQLException, DataException {
        //update the DB
        PreparedStatement pstmt = conn.prepareStatement("UPDATE BackupData SET ext = ?, thisFileName = ?, " +
                "fileSize = ?, dateUploaded = ?, Status = ?, MembershipID = ?, fileType = ? WHERE BackupID = ?");
        pstmt.setString(1, bkData.getExt());
        pstmt.setString(2, bkData.getFileName());
        pstmt.setDouble(3, bkData.getFileSize());
        pstmt.setDate(4, java.sql.Date.valueOf(bkData.getDateUploaded()));
        pstmt.setString(5, bkData.getStatus());
        pstmt.setString(6, bkData.getMembershipID());
        pstmt.setString(7, bkData.getFileType());
        pstmt.setString(8, bkData.getId());
        pstmt.executeUpdate();
        pstmt.close();
        bkData.setAlreadyInDB(true);
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL insert statement and make it more readable.  But
     * logically, it's really just a part of save.
     * 
     * 
     * @param bkData contains the BackupDataBO to be updated to the DB
     * @param conn contains the connection already established with the DB
     * @throws edu.byu.isys413.group1E.handlers.DataException handles any errors from data
     * @throws java.sql.SQLException catches any errors from the SQL execution
     */
    private synchronized void insert(BackupDataBO bkData, Connection conn) throws SQLException, DataException {
        //update the DB
        PreparedStatement pstmt = conn.prepareStatement("INSERT INTO BackupData (BackupID, ext, thisFileName, fileSize, " +
                "dateUploaded, Status, MembershipID, fileType) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        pstmt.setString(1, bkData.getId());
        pstmt.setString(2, bkData.getExt());
        pstmt.setString(3, bkData.getFileName());
        pstmt.setDouble(4, bkData.getFileSize());
        pstmt.setDate(5, java.sql.Date.valueOf(bkData.getDateUploaded()));
        pstmt.setString(6, bkData.getStatus());
        pstmt.setString(7, bkData.getMembershipID());
        pstmt.setString(8, bkData.getFileType());
        pstmt.executeUpdate();
        pstmt.close();
        bkData.setAlreadyInDB(true);
    }
    
    
    ///////////////////////////////////////////////////////////////////////////////
    /////////   DELETE
    
    /**
     * I included the delete functionality here because when a member requests to delete a file, the file
     * is removed from this table and placed in the RecycleBin table.
     * 
     * @param bkDataID contains the id of the item to be deleted
     * @throws java.sql.SQLException catches any errors from the SQL execution
     * @throws edu.byu.isys413.group1E.handlers.DataException handles any errors from data
     * @throws edu.byu.isys413.group1E.handlers.ConnectionPoolException catches any errors with the connection
     *
     */
    public synchronized void delete(String bkDataID) throws SQLException, DataException, ConnectionPoolException {
        //update the DB
        Connection conn = ConnectionPool.getInstance().get();
        PreparedStatement pstmt = conn.prepareStatement("DELETE FROM BackupData WHERE BackupID = ?");
        pstmt.setString(1, bkDataID);
        pstmt.executeUpdate();
        pstmt.close();
        ConnectionPool.getInstance().release(conn);
    }
    
}
